// scroll_fixed=====================================================
kktj_scroll_fixed=function(_parm){
// id,foot_classname,foot_distence,offsettop,callback_a,callback_b
        var parm= $.extend({
                    },_parm);

            var id=parm.id
            foot_classname=parm.foot_classname,
            foot_distence=parm.foot_distence,
            offsettop=parm.offsettop,
            callback_a=parm.callback_a,
            callback_b=parm.callback_b;

        var c=offsettop;
        $(window).scroll(function (){
            changePosa_(id, _getHeight,tofoot, obj);
        });
        var getobj=function(id){
        var obj=id.match(/\./g)?function(id){var obj = $(id).eq(0)[0];return obj }(id):
        function(id){
        var obj= $("#"+id).eq(0)[0];
        return obj}(id);
        return obj;
        };
        var obj=getobj(id);
        var _getHeight=c?getobj(c).offsetTop:obj.offsetTop;
        var uu=function(){
            var a=$("."+foot_classname).offset().top;
            return a;
        }
        var foot_offset_h=typeof(foot_classname)=="undefined"?$("body").height():$("."+foot_classname).offset().top;//foot offsettop
        
        var obj_margintop=Number($(obj).css("marginTop").replace("px",""))||0;
        var foot_distence=typeof(foot_distence)=="undefined"?"0":foot_distence;
        var tofoot=foot_offset_h-$(obj).height()-Number(foot_distence.replace("px",""))||0;

        function changePosa_(id, height, foot, obj) {
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            if (scrollTop < height) {
                obj.style.position = 'relative';
                obj.style.marginTop = '';
                typeof(callback_a)=="undefined"?"":callback_a($(obj).height());
            } else {
                typeof(callback_b)=="undefined"?"":callback_b($(obj).height());
                scrollTop>foot?function(){ obj.style.position = 'relative';obj.style.marginTop = '0';obj.style.top = (foot-height+obj_margintop)+"px"; }():
                function(){
                obj.style.position = 'fixed';
                obj.style.top = '0';
                obj.style.marginTop = '0';}();
            }
        }
};
// scroll_fixed=====================================================end


// model box begin=============================================================
function model_box(data){
// argument include under===========yijiabin 20160526
// btn
// model_inner_content
// close_btn
// callback
    var arg=$.extend({},data);
    var a=arg.btn,b=arg.model_inner_content,c=arg.close_btn,d=arg.callback;
    var btn=$(a);
    var box=$(b);
    var closebtn=$(c);
    $(document).on("click",a,function(){
        $("#model_box").fadeIn(150);
        $("body").addClass("modelopen");
        box.fadeIn(100);
        setTimeout(function(){box.addClass("animate");},50);
        if(d){eval(d);};//callback function
    });
    $("#model_box").click(function(){
        $(this).fadeOut(500);
        $(".model_box_content").removeClass("animate").fadeOut(80);
        $("body").removeClass("modelopen");
    })
    var f=c?closebtn:$('#model_box').find(".close");//判断有没设置关闭按钮
    f.click(function(event){            
      $('.model_box_content').removeClass("animate").fadeOut(80);
      $('#model_box').fadeOut(500);
      $("body").removeClass("modelopen");
    });
    $('.model_box_content').click(function(event){
        event.stopPropagation();
    });    
}
// model box end=============================================================



//tipbox begin===============================================================
// 套餐详情页
// 机构列表页
// target:
// tipboxdir:
// tipbox_remain_shown :
function tipbox(data){
    var arg=$.extend({},data);
    var a=$(arg.target); 

    a.on("mouseenter",function(){
        var _this=$(this);
        var bb=function(){
                $(".kktipbox").remove();
                $(".kktipbox_point_box").remove();
        var dir=_this.data("tipboxdir");
        arg.dir?(dir=arg.dir):(dir?"":dir="right");

        var html01="<div class='kktipbox kktipbox_"+dir+"'></div>";
        var html02="<div class='kktipbox_point_box'><div class='kktipbox_point kktipbox_point_"+dir+"'></div></div>";

        //if the target elemment is td ，set the appending html out of table
        if(a.is('td')){
            a.eq(0).parent().parent().parent().after(html01);
            a.eq(0).parent().parent().parent().after(html02);
        }else{
            a.eq(0).after(html01);
            a.eq(0).after(html02);
        };

        var top_margin=a.eq(0).css("marginTop")?Number(a.eq(0).css("marginTop").replace("px","")):0;
        var left_margin=a.eq(0).css("marginLeft")?Number(a.eq(0).css("marginLeft").replace("px","")):0;
        var left;
        var top=_this.position().top;
        var w=_this.innerWidth();
        var h=_this.innerHeight();
        var txt=_this.data("tipbox");
        var _top;
        var kktipbox_top;
        var kktipbox_left;
        var h_icon=$('.kktipbox_point').innerHeight();
        var w_icon=$('.kktipbox_point').innerWidth(); 
        $(".kktipbox").text("").text(txt);

        if (dir=="right") {_top=top+top_margin-h_icon/2;left=_this.position().left+w;};
        if (dir=="bottom")  {_top=top+top_margin+h;left=_this.position().left;};
        if (dir=="top")  {_top=top+top_margin-h;left=_this.position().left;};
        if (dir=="left")  {_top=top+top_margin-h_icon/2;left=_this.position().left-w;};

        $(".kktipbox_point_box").css({"height":h,"width":w,"top":_top,"left":left}).show(0).addClass("active");       
        $(".kktipbox").css({"height":"auto","width":"auto"});
        var box_h=$(".kktipbox").outerHeight();
        var box_w=$(".kktipbox").outerWidth();

        if (dir=="right"){kktipbox_top=top+top_margin-(box_h-h)/2;kktipbox_left=(left+w_icon-1)}
        if (dir=="bottom") {kktipbox_top=top+top_margin+h+h_icon-1;kktipbox_left=left+left_margin-(box_w-w)/2}
        if (dir=="top"){kktipbox_top=top+top_margin-h_icon-box_h+1;kktipbox_left=left+left_margin-(box_w-w)/2}
        if (dir=="left"){kktipbox_top=top+top_margin-(box_h-h)/2;kktipbox_left=(left-box_w+w-w_icon+1)}

        $(".kktipbox").css({"height":$(".kktipbox").height(),"width":$(".kktipbox").width(),"top":kktipbox_top,"left":kktipbox_left}).show(0).addClass("active");
        }

        if(arg.tipbox_remain_show){setTimeout(function(){bb()},1);}else{
        bb();
        }//this is need to seting because when the two target is neighbor and have no diatance from each other,the mouseleve whill excute function 1 milisecond later

        });
        var mouseout_hide=true;//key variable of hiding or showing tipbox 
        var hidetipbox=function(){
            $(".kktipbox_point_box").hide(0);
            $(".kktipbox").hide(0);
            $(".kktipbox").removeClass("active").remove();
            $(".kktipbox_point_box").removeClass("active").remove();
        }
        a.on("mouseleave",function(){
            if(arg.tipbox_remain_show){
            setTimeout(function(){
                if(!mouseout_hide){mouseout_hide=true;return};
                hidetipbox();
            },1)
            }else{
                hidetipbox();
            }
        });


        // =============if the mouse moveover ，set the tipbox hide or remain showing
        if(arg.tipbox_remain_show){
        $("body").on("mouseenter",'.kktipbox_point_box',function(event){
             mouseout_hide=false;
        });
        $("body").on("mouseout",'.kktipbox_point_box',function(event){
            setTimeout(function(){
            if(!mouseout_hide){mouseout_hide=true;return}
            hidetipbox();
            },1)
        });
        $("body").on("mouseenter",'.kktipbox',function(event){
            mouseout_hide=false;
        });
        $("body").on("mouseout",'.kktipbox',function(event){
            setTimeout(function(){
            if(!mouseout_hide){return}
            hidetipbox();
            },103)
        });
        }
   }

//tipbox end===================================================================









// calender 插件===============================================================
   function showdate(json, showyear, showmonth) {

//当月数据，当月年份，当月月份，提前天数,删除天数（数组）
    /*日历*/
    var solarMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    var nStr1 = new Array('日', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十');
    //返回公历y年m+1月的天数
    function solarDays(y, m) {
        if (m == 1)
            return (((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0)) ? 29 : 28);
        else
            return (solarMonth[m]);
    }
    //记录公历的日期
    function calElement(sYear, sMonth, sDay, week) {
        this.isToday = false;
        //公历
        this.sYear = sYear;
        this.sMonth = sMonth;
        this.sDay = sDay;
        this.week = week;
    }
    //保存y年m+1月的相关信息
    function calendar(y, m) {
        var sDObj;
        sDObj = new Date(y, m, 1);  //当月第一天的日期
        this.length = solarDays(y, m);    //公历当月天数
        this.firstWeek = sDObj.getDay(); //公历当月1日星期几
        for (var i = 0; i < this.length; i++) {
            this[i] = new calElement(y, parseInt(m)+ 1, i + 1, nStr1[(i + this.firstWeek) % 7]);
            if ((i + this.firstWeek) % 7 == 0) {
                this[i].color = '#ccc';  //周日颜色
            }
        }
        if (y == tY && m == tM) this[tD - 1].isToday = true;    //今日
    };

    var cld;
    function drawCld(SY, SM) {
        var i, sD;
        var icon="icon01"//定义角标匹配的class
        cld = new calendar(SY, SM);
        var recommendday=false;
        for (i = 0; i < 42; i++) {
            var sObj = $('#SD' + i);
            var lObj = $('#LD' + i);
            sObj.parent().removeClass("active");
            sD = i - cld.firstWeek;
            //计算提前天数
            var Today = new Date();
            function AddDays(date,value) {
                return new Date(Date.parse(date) + (86400000 * (value - 1)));
            };
            var leadtime = AddDays(Today, tqts);
            sObj.parent("td").removeClass("recommendday");
            if (sD > -1 && sD < cld.length) { //日期内
                sObj.text(sD + 1);
                sObj.data("date", SY + "-" + (SM + 1) + "-" + (sD + 1));
                sObj.parent("td").removeClass(icon);
                if (alldaty[parseInt(sD)].flag && new Date(SY, SM, sD + 1) > leadtime) {
                    sObj.parent().addClass("active");
                    sObj.next("span").text(alldaty[parseInt(sD)].count);
                    sObj.parent("td").data("date",SY+"-"+(SM+1)+"-"+(sD + 1));
                    var $delweekday=xxr;//指定星期几休息变量
                    _delweekday=$delweekday.split("|");
                    var is_delweekday=false;
                    for(var n = 0; n < _delweekday.length; n++) {
                    if(new Date(SY, SM, sD+1).getDay()==_delweekday[n]&&_delweekday[n].length>0){//指定星期几休息
                        sObj.parent().removeClass("active");
                        lObj.text("休息");
                        is_delweekday=true;
                    }
                    };
                    if(!recommendday&&SM==tM&&!is_delweekday){
                    sObj.parent("td").addClass("recommendday");
                    recommendday=true;
                    };

                }
                else {
                    if (new Date(SY, SM, sD+1) >=new Date(tY,tM,tD) && new Date(SY, SM, sD+1)< leadtime ){
                       sObj.parent("td").addClass(icon);//给提前的几天加角标class
                       lObj.text(""); 
                       sObj.parent("td").data("tipbox","需提前"+tqts+"天预约");
                    }else{
                       lObj.text(""); 
                    }
                }

                if(alldaty[parseInt(sD)].txt){
                //加节假日注释和约满判断
                    if(alldaty[parseInt(sD)].dataflag==1){
                    lObj.text(alldaty[parseInt(sD)].txt);

                    }else{
                        lObj.text("");sObj.parent("td").addClass(icon);
                        sObj.parent("td").data("tipbox",alldaty[parseInt(sD)].txt);
                    };
                    
                };
                sObj.parent("td").removeClass("isToday");
                if (cld[sD].isToday) {sObj.parent("td").addClass("isToday");sObj.next("span").text("今天");
                sObj.parent().removeClass("active");//设置今天不可点击 
                }; //今日颜色

                   
            }
            else { //非日期
                sObj.text("");
                lObj.text("");
                sObj.parent("td").removeClass(icon);
            }
        }
        var $ptext = $(".tablediv tbody tr:last td:first p:first");
        if ($ptext.text()) {
            $ptext.parents("tr").css("display", "table-row");
        } else {
            $ptext.parents("tr").css("display", "none");
        }
    }
    //用自定义变量保存当前系统中的年月日
    var Today = new Date();
    var tY = Today.getFullYear();
    var tM = Today.getMonth();
    var tD = Today.getDate();
    //设置的时间
    var setYear = tY;
    var setMonth = tM;
    //打开页时,在下拉列表中显示当前年月,并调用自定义函数drawCld(),显示公历和农历的相关信息
    var alldaty = [];//保存所以天数数据
    var nowdat = [];
    var xxr;
    var tqts;
    if (json) {
        // json.returnDay.sort(function (a, b) {
        //     var time1 = new Date(a);
        //     var time2 = new Date(b);
        //     return time1 - time2;
        // });

    if(typeof json!=="string"){}else{json=JSON.parse(json);};       
        nowdat = json.data;
        xxr=json.xxr;
        tqts=json.tqts;
    }
    function initial(y, m) {
        var datalength = solarDays(y, m);
        var noday = 0;//保存没有日期下一天位置
        var sDObj = new Date(y, m, 1);//当月第一天
        var firstWeek = sDObj.getDay(); //公历当月1日星期几
        alldaty = [];//清空当月数据
        
        for (var i = 0; i < datalength; i++) {
            var nowday = new Date(y, m, i + 1);//当天时间;
            var nowWeek = nowday.getDay(); //公历当月当日星期几
            var obj = {};
            obj.TJRQ = i;
            var isdelday = true;
            var str=[];
            var m01=m+1;
            var d01=i+1;
            str.push(y,m.toString().length<2&&m!==9?"0"+m01:m01,d01.toString().length<2?"0"+d01:d01);
            var str01=str.join("-");
            var k;
            for(var z=0;z<nowdat.length;z++){
                if (nowdat[z].date==str01) {
                    // var deleteday = (new Date(nowdat[noday].date.replace(/-/g, "/")));
                    k=z;
                    isdelday = false //如果是0，为删除天
                } 
            }
            if (!isdelday) {
                //obj.count="不可约";
                obj.count ="";
                obj.txt =nowdat[k].text;
                obj.dataflag=nowdat[k].flag;
                obj.flag = false;
                noday++;
            } else {

                obj.count = "可约";
                obj.flag = true;
            };
            alldaty.push(obj);
        };
        $(".controldiv p").html(y + "<span>年</span>" + (m + 1) + "<span>月</span>");
        var prev = {};
        var next = {};
        if (setMonth == 0) {
            prev.year = setYear - 1;
            prev.month = 11;
            next.year = setYear;
            next.month = setMonth + 1;

        } else if (setMonth == 11) {
            prev.year = setYear;
            prev.month = setMonth - 1;
            next.year = setYear + 1;
            next.month = 0;
        } else {
            prev.year = setYear;
            prev.month = setMonth - 1;
            next.year = setYear;
            next.month = setMonth + 1;
        }
        $(".controldiv a.left").data("year", prev.year).data("month", prev.month);
        $(".controldiv a.right").data("year", next.year).data("month", next.month);
        drawCld(y, m);
    };

    setYear = showyear;
    setMonth = showmonth;
    initial(setYear, setMonth); //初始化日历控件
};

    var showtable = function (elemment) {
        var gNum;
        var trarr = [];
        var trstr = "";
        for (var i = 0; i < 6; i++) {
            trstr = '<tr align="center">';
            for (var j = 0; j < 7; j++) {
                gNum = i * 7 + j;
                trstr += '<td id="GD' + gNum + '"><p id="SD' + gNum + '"></p><span id="LD' + gNum + '"></span></td>';
            }
            trstr += '</tr>';
            trarr.push(trstr);
        }
        elemment.append(trarr.join(""));
        $(elemment).find("tr:odd").addClass("color01");
    }

    showtable($(".tablediv tbody"));

/*加减按钮 在页面里定义*/
// $(".controldiv").on("click", "a.left,a.right", function () {
//     var $this = $(this);
//     var getyear = $this.data("year");
//     var germonth = $this.data("month");

//     $.ajax({
//              url: "calenderjson.json",
//              async:"true",
//              dataType:"json",
//              type:"get",
//              success: function(data){
//              showdate(data, getyear, germonth);
//              $("")

//                },
//                error:function(){
//             alert("flase")
//                }
//     }); 

// });

//一开始先加载渲染日历 在页面里定义
// stratshowdate=function(){
// $.ajax({
//          url: "calenderjson.json",
//          async:"true",
//          dataType:"json",
//          type:"get",
//          success: function(data){
// showdate(data, new Date().getFullYear(), new Date().getMonth());

//            },
//            error:function(){
// alert("flase")
//            }
//   });
// };
// stratshowdate();
// calender插件 end==============================================================





//kk_dropdown插件

//btn_box
//drop_box
//wrap_box
kk_dropdown=function(a){
    var args= $.extend({},a);
    var btn=$(args.btn_box),drop_box=$(args.drop_box),wrap_box=$(args.wrap_box);
    // wrap_box.click(function(event){event.stopPropagation()});
    wrap_box.on("click",args.btn_box,function(){
        if(wrap_box.hasClass("dropdown_active")){
        wrap_box.find(args.drop_box).hide().addClass("hide");
        wrap_box.removeClass("dropdown_active");
        }else{
        wrap_box.find(args.drop_box).show().removeClass("hide");
        wrap_box.addClass("dropdown_active");
        }
    });
    $("body").on("click",function(e){
      var on=false;

        for(var i = 0;i<btn.length; i++) {
           if(e.target==btn[i]){on=true}
        };

      if(on){return}else{wrap_box.find(args.drop_box).hide().addClass("hide");
      wrap_box.removeClass("dropdown_active");
  }
    });
}